#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import os
import time
import subprocess
import socket
import json
import tkinter as tk
import RPi.GPIO as GPIO

from tkinter import ttk
from tkinter import messagebox

import config

BUFSIZE = 1460

server_address = '/tmp/gpio_socket'
conf = {}

playing_group = []


def gpio_init(sock):
    GPIO.cleanup()
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(config.ic_card_pin, GPIO.IN, GPIO.PUD_UP)

    conf = {}
    for i in range(1, config.GROUP_NUM + 1):
        conf['gpio'] = config.group["pin.%d" % i]
        conf['level'] = config.group["worklevel.%d.off" % i]
        sock.sendall(json.dumps(conf).encode())
        data = sock.recv(BUFSIZE)
        print('recv from svr:', data)


def gpio_deinit():
    GPIO.setmode(GPIO.BCM)
    GPIO.cleanup()


class Step1():
    """docstring for Step1"""
    def __init__(self, window, img, sock):
        # super(Step1, self).__init__()
        self.window = window
        self.img = img
        self.sock = sock
        self.window.geometry('440x400')

        self.interface = tk.Frame(self.window,)
        self.interface.pack()

        label5 = tk.Label(self.interface, image=img)
        label5.grid(row = 0, column = 0)

        check = tk.Button(self.interface, text = '查看监控',
                                        command = self.check_ic_card,
                                        width = 12,
                                        font = ('Arial', 12))
        check.grid(row = 2, column = 0)

    def check_ic_card_test(self):
        self.interface.destroy()
        Step2(self.window, self.sock)

    def check_ic_card(self):
        print("get ic_card_pin %d" % GPIO.input(config.ic_card_pin))
        if GPIO.input(config.ic_card_pin) == 0:
            self.interface.destroy()
            Step2(self.window, self.sock)
        else:
            msgbox = messagebox.showwarning(title='警告', message=config.forbid)


class Step2():
    """docstring for Step2"""
    def __init__(self, window, sock):
        super(Step2, self).__init__()
        self.window = window
        self.sock = sock
        self.window.geometry('540x60')

        self.interface = tk.Frame(self.window,)
        self.interface.grid(row = 0, column = 0)

        # 选择地点
        label1 = tk.Label(self.interface, text = "地点",
                                        bg = 'green',
                                        width = 8,
                                        font = ('Arial', 12),)
        label1.grid(row = 0, column = 0, sticky = tk.N + tk.S)


        self.location = ttk.Combobox(self.interface, width = 16,
                                                    font = ('Arial', 12))
        self.location['value'] = config.total_addr
        self.location.current(0)
        # self.location.bind("<<ComboboxSelected>>", get_addr_time)
        self.location.grid(row = 0, column = 1, sticky = tk.N + tk.S)

        # 选择时间
        label2 = tk.Label(self.interface, text = "时间",
                                        bg = 'green',
                                        width = 8,
                                        font = ('Arial', 12))
        label2.grid(row = 0, column = 2, sticky = tk.N + tk.S)


        self.time = tk.Entry(self.interface, show = None,
                                            width = 24,
                                            font = ('Arial', 12))  # 显示成明文形式
        self.time.grid(row = 0, column = 3, sticky = tk.N + tk.S)

        # 输入密码
        # label3 = tk.Label(self.interface, text = "密码",
        #                                 bg = 'green',
        #                                 width = 8,
        #                                 font = ('Arial', 12))
        # label3.grid(row = 0, column = 4, sticky = tk.N + tk.S)


        # self.secret = tk.Entry(self.interface, show = None,
        #                                     width = 24,
        #                                     font = ('Arial', 12))  # 显示成明文形式
        # self.secret.grid(row = 0, column = 5, sticky = tk.N + tk.S)


        check = tk.Button(self.interface, text = '查看监控',
                                        command = self.get_info,
                                        width = 12,
                                        height = 1,
                                        font=('Arial', 12))
        check.grid(row = 1, column = 3)


        notice = tk.StringVar()
        notice.set("[注意]\n1. 时间格式：2019-09-09")
        label4 = tk.Label(self.interface, textvariable = notice,
                                        justify = "left")
        label4.grid(row = 1, column = 0, columnspan = 3, sticky = tk.W)


    def get_info(self):

        right = False

        # print(self.location.get())
        # print(self.time.get())
        # print(self.secret.get())

        # if playing vedio
        for i in range(1, config.KEY_NUM + 1):
            if config.key["location.%d" % i] == self.location.get() and config.key["date.%d" % i] == self.time.get():

                right = True

                if not (i in playing_group):
                    playing_group.append(i)
                    print("append %d" % i)
                
                print(playing_group)

                # pid = subprocess.Popen(["mplayer", "-fs", config.key["video.%d" % i]])
                # print("playing")
                # time.sleep(config.key["vsize.%d" % i])
                # print("play complete")
                # pid.terminate()

                subprocess.run(["mplayer", "-fs", config.key["video.%d" % i]])

        if right == True:
            # if need gpio control
            for i in range(1, config.GROUP_NUM + 1):
                trigger_gpio = True

                for idx in config.group["part.%d" % i]:
                    if not (idx in playing_group):
                        trigger_gpio = False

                if trigger_gpio == True:
                    conf = {}
                    conf['gpio'] = config.group["pin.%d" % i]
                    conf['level'] = config.group["worklevel.%d.on" % i]
                    self.sock.sendall(json.dumps(conf).encode())
                    data = self.sock.recv(BUFSIZE)
                    print('recv from svr:', data)

                    # GPIO.output(config.group["pin.%d" % i], config.group["worklevel.%d.on" % i])
                    print("output %d level %d" % (config.group["pin.%d" % i], config.group["worklevel.%d.on" % i]))
        
        else:
            msgbox = messagebox.showwarning(title='警告', message=config.warning)
